import { request } from '@umijs/max';
import { message, notification } from 'antd';
import { setAuthHeader } from './authInterceptor';

const showNotificationError = (message: string, description?: string) => {
  notification.error({
    message,
    description,
  });
};

const baseRequest = async (url: string, params?: any) => {
  try {
    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
    };

    // 添加认证头
    setAuthHeader(headers);

    const response = await request(`/api${url}`, {
      method: 'POST',
      headers,
      data: params,
      timeout: 30 * 60,
    });

    // 对于退出登录接口，返回完整的响应对象
    if (url === '/auth/logout') {
      return Promise.resolve(response);
    }

    if (response && response.code !== undefined) {
      console.log(response.code);

      switch (response.code) {
        case 200: // 修改为API文档中的成功状态码
          // 接口成功
          return Promise.resolve(response.data);
        case 401:
          // 登录失效
          message.info('登录失效，请重新登录');
          window.location.href = '/login';
          break;
        case 403:
          // 权限不足
          showNotificationError('权限不足', '您没有权限执行此操作');
          break;
        default:
          showNotificationError(response.message || '请求失败', `错误码: ${response.code}`);
          return Promise.reject(response);
      }
    } else {
      // 响应结果不是对象
      return Promise.resolve(response);
    }
  } catch (error: any) {
    if (error.response) {
      switch (error.response.status) {
        case 401:
          // 登录失效
          window.location.href = '/login';
          break;
        case 403:
          // 没有权限
          showNotificationError('权限不足', '您没有权限执行此操作');
          break;
        case 404:
          // 接口不存在
          showNotificationError('请求地址不存在', error.config.url);
          break;
        default:
          showNotificationError('请求失败', error.message || '未知错误');
          break;
      }
    }
    return Promise.reject(error);
  }
};

/**
 * post 请求
 * @param url
 * @param data
 * @returns
 */
export const post = async (url: string, data?: any) => baseRequest(url, data);
